#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import requests
# 调用一个接口API获取官网值，
def get_token():
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=lVfov6E1oaWZR9f4qIhd9Hjy&client_secret=Gubrc6RnMTdA3Eb8WumHIGrz4vHgCTdy'
    content=requests.get(host).content.decode()
    content=eval(content[:-1])#eval()
    return content['access_token']
# 读取图片二进制数据
# 二进制方式打开图文件
def imgdata(file1path,file2path):
    import base64
    with open(file1path,'rb') as f:
        pic1=base64.b64encode(f.read())
    with open(file2path,'rb') as f:
        pic2=base64.b64encode(f.read())
    params=json.dumps(
        [
            {"image":str(pic1,"utf-8"),"image_type":"BASE64","face_type":"LIVE","quality_control":"LOW"},
            {"image": str(pic2, "utf-8"), "image_type":"BASE64", "face_type": "IDCARD", "quality_control": "LOW"}
        ]
    )
    return params.encode(encoding='UTF-8')
# 进行对比获得结果
def img(file1path,file2path):
    print('正在调用人脸识别接口...!')
    token=get_token()
    print("正在解析人脸图像...!")
    params=imgdata(file1path,file2path)
    print('params:',params)
    request_url = "https://aip.baidubce.com/rest/2.0/face/v3/match"+"?access_token="+token
    print('request_url:',request_url)
    content=requests.post(request_url,data=params).content
    print('content:',content)
    content=eval(content)
    print(content)
    # score=content['result']['score']
    # if score>90:
    #     print('照片相似度%s，是同一个人'% score)
    # else:
    #     print('照片相似度%s，不是同一个人'% score)
if __name__=='__main__':
    img('马云1.jpg','马云2.jpg')